import * as vscode from 'vscode';
import * as path from 'path';
import { I18nDefinitionProvider } from './providers/definitionProvider';
import { I18nCompletionProvider } from './providers/completionProvider';
import { I18nSemanticTokenProvider } from './providers/semanticTokenProvider';
import { I18nColorProvider } from './providers/colorProvider';
import { I18nReferenceProvider } from './providers/referenceProvider';
import { I18nService, UntranslatedEntry } from './services/i18nService';

export function activate(context: vscode.ExtensionContext) {
    console.log('FastAPI I18n Helper is now active!');

    // Initialize services
    const i18nService = new I18nService();
    const colorProvider = new I18nColorProvider();

    // Register providers
    const definitionProvider = new I18nDefinitionProvider(i18nService);
    const completionProvider = new I18nCompletionProvider(i18nService);
    const semanticTokenProvider = new I18nSemanticTokenProvider(i18nService);
    const referenceProvider = new I18nReferenceProvider(i18nService);

    // Register the providers with VS Code
    context.subscriptions.push(
        vscode.languages.registerDefinitionProvider(
            { scheme: 'file', language: 'python' },
            definitionProvider
        ),
        vscode.languages.registerDefinitionProvider(
            { scheme: 'file', language: 'json', pattern: '**/i18n/*.json' },
            definitionProvider
        ),
        vscode.languages.registerCompletionItemProvider(
            { scheme: 'file', language: 'python' },
            completionProvider,
            't', '(', '"', "'" // Trigger completion after t, (, and quotes
        ),
        vscode.languages.registerDocumentSemanticTokensProvider(
            { scheme: 'file', language: 'python' },
            semanticTokenProvider,
            semanticTokenProvider.legend
        ),
        vscode.languages.registerReferenceProvider(
            { scheme: 'file', language: 'json', pattern: '**/i18n/*.json' },
            referenceProvider
        )
    );

    // Register commands
    context.subscriptions.push(
        vscode.commands.registerCommand('i18n-helper.reloadTranslations', () => {
            i18nService.reloadTranslations();
            vscode.window.showInformationMessage('I18n translations reloaded');
        }),
        vscode.commands.registerCommand('i18n-helper.addTranslation', async () => {
            const key = await vscode.window.showInputBox({
                prompt: 'Enter translation key (e.g., auth.login.success)',
                placeHolder: 'Translation key'
            });

            if (key) {
                const value = await vscode.window.showInputBox({
                    prompt: `Enter translation value for key "${key}"`,
                    placeHolder: 'Translation value'
                });

                if (value) {
                    const success = await i18nService.addTranslation(key, value);
                    if (success) {
                        vscode.window.showInformationMessage(`Translation added: ${key} = ${value}`);
                    }
                }
            }
        }),
        vscode.commands.registerCommand('i18n-helper.scanUntranslated', async () => {
            const progress = await vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: "Scanning for untranslated keys...",
                cancellable: false
            }, async (progress) => {
                progress.report({ increment: 0 });

                // Scan for untranslated keys
                const untranslatedKeys = await i18nService.scanForUntranslatedKeys();
                if (untranslatedKeys.length === 0) {
                    vscode.window.showInformationMessage('No untranslated keys found.');
                    return;
                }

                // Group keys by their module (first part of the key)
                const groupedKeys = new Map<string, UntranslatedEntry[]>();
                for (const entry of untranslatedKeys) {
                    const module = entry.key.split('.')[0];
                    if (!groupedKeys.has(module)) {
                        groupedKeys.set(module, []);
                    }
                    groupedKeys.get(module)!.push(entry);
                }

                progress.report({ increment: 50, message: "Found " + untranslatedKeys.length + " untranslated keys" });

                // Create QuickPick items for each untranslated key
                const items = untranslatedKeys.map(entry => ({
                    label: entry.key,
                    description: `(${path.basename(entry.sourceFile)}:${entry.line})`,
                    picked: true, // All items selected by default
                    entry
                }));

                // Show QuickPick with all untranslated keys
                const selected = await vscode.window.showQuickPick(items, {
                    canPickMany: true,
                    placeHolder: `Found ${untranslatedKeys.length} untranslated keys. Select keys to add empty translations for.`
                });

                if (!selected || selected.length === 0) {
                    return;
                }

                progress.report({ increment: 75, message: "Adding empty translations..." });

                // Create translations map with empty strings
                const translations = new Map<string, string>();
                for (const item of selected) {
                    translations.set(item.label, "");
                }

                // Add all translations in batch
                if (translations.size > 0) {
                    const success = await i18nService.batchAddTranslations(translations);
                    if (success) {
                        vscode.window.showInformationMessage(
                            `Successfully added ${translations.size} empty translations`
                        );
                    }
                }

                progress.report({ increment: 100 });
            });
        })
    );

    // Watch for active editor changes
    vscode.window.onDidChangeActiveTextEditor(editor => {
        if (editor && editor.document.languageId === 'python') {
            updateDecorations(editor);
        }
    }, null, context.subscriptions);

    // Watch for document changes
    vscode.workspace.onDidChangeTextDocument(event => {
        const editor = vscode.window.activeTextEditor;
        if (editor && event.document === editor.document) {
            updateDecorations(editor);
        }
    }, null, context.subscriptions);

    // Initial decoration update
    if (vscode.window.activeTextEditor) {
        updateDecorations(vscode.window.activeTextEditor);
    }

    // Function to update decorations
    function updateDecorations(editor: vscode.TextEditor) {
        const text = editor.document.getText();
        const validRanges: vscode.Range[] = [];
        const invalidRanges: vscode.Range[] = [];

        // Updated pattern to be more specific about t() function calls
        const pattern = /(?<![.\w])t\(['"]([\w\.]+)['"]\)/g;
        let match;

        while ((match = pattern.exec(text))) {
            const startPos = editor.document.positionAt(match.index + 3);
            const endPos = editor.document.positionAt(match.index + 3 + match[1].length);
            const range = new vscode.Range(startPos, endPos);

            if (i18nService.isValidTranslationKey(match[1])) {
                validRanges.push(range);
            } else {
                invalidRanges.push(range);
            }
        }

        colorProvider.updateDecorations(editor, validRanges, invalidRanges);
    }
}

export function deactivate() {
    // Clean up resources
} 